package com.eunion.web.cms.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eunion.core.LogUtil;
import com.eunion.core.common.DeleteVo;
import com.eunion.core.common.JsonVo;
import com.eunion.core.common.response.ResponseList;
import com.eunion.core.exception.ValidateException;
import com.eunion.web.cms.entity.MajorType;
import com.eunion.web.cms.entity.spec.MajorTypeSpec;
import com.eunion.web.cms.service.MajorTypeService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;

/**
 * 专业分类
 */
@Controller
@RequestMapping("/api/major-types")
@PreAuthorize("hasAuthority('major:admin:major_type')")
public class MajorTypeResource extends BaseTableCommonController<MajorType, Long> {

    private final Logger log = LoggerFactory.getLogger(MajorTypeResource.class);

    @Autowired
    private MajorTypeService majorTypeService;

    @Override
    protected BaseService<MajorType, Long> getBaseService() {
        return majorTypeService;
    }

    /**
     * 进入专业分类页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/majortype/majortype";
    }

    /**
     * 通用的查询接口
     * @param queryBean
     * @return
     */
    @PostMapping("/findAll")
    @ResponseBody
    public ResponseList<MajorType> findAll(@RequestBody MajorType queryBean) {
        Sort sort = new Sort("majorTypeCode");
        List<MajorType> list = majorTypeService.findAll(MajorTypeSpec.build(queryBean), sort);
        return new ResponseList<MajorType>(HttpStatus.OK, list);
    }

    /**
     * 添加。
     * 表单提交接收对象不能使用@RequestBody
     */
    @PreAuthorize("hasAuthority('major_type:add')")
    @PostMapping(value = Web.URL_SEP_SAVE, produces = {"application/json;charset=UTF-8"})
    public String save(MajorType obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                        throw new ValidateException(error.getDefaultMessage());
                    }
                }
            }

            // 对专业分类代码校验唯一性。
            MajorType queryBean = new MajorType();
            queryBean.setMajorTypeCode(obj.getMajorTypeCode());
            List<MajorType> list = majorTypeService.findAll(MajorTypeSpec.build(queryBean));
            if (list != null && list.size() > 0) {
                setModuleStatusError(model, "专业分类代码重复，请检查！");
            } else {
                getBaseService().save(obj);
                setModuleStatusOK(model, "添加成功");
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "添加失败");
        }
        setModuleAdd(model);
        return getUrlBase().concat("-add");
    }

    /**
     * 修改。
     * 表单提交接收对象不能使用@RequestBody
     */
    @PostMapping(value = Web.URL_SEP_UPDATE, produces = {"application/json;charset=UTF-8"})
    public String update(MajorType obj, BindingResult result, Model model) {
        try {
            majorTypeService.save(obj);
            setModuleStatusOK(model, "修改成功");
        } catch (Exception e) {
            LOG.error("update MajorType error : {}", e);
            setModuleStatusError(model, "修改失败");
        }
        setModuleEdit(model);
        model.addAttribute(Web.OBJ, obj);
        return getUrlBase().concat("-edit");
    }

    /**
     * 根据传入的数据ids,来删除对象.
     */
    @PostMapping(value = Web.URL_SEP_REMOVE)
    @ResponseBody
    protected JsonVo remove(@RequestBody DeleteVo<Long> dvo) {
        try {
            if (dvo != null && dvo.getIds() != null && dvo.getIds().size() > 0) {
                return super.remove(dvo);
            }
            return new JsonVo(true);
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("remove error ", e);
            return new JsonVo(false, "删除失败");
        }
    }
}
